﻿using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using AutomaticSubtitles.Service.Infrastructure.BaiduTrans.Model;
using Microsoft.AspNetCore.WebUtilities;

namespace AutomaticSubtitles.Service.Infrastructure.BaiduTrans;

public class BaiduTransApicSharpService
{
    private readonly HttpClient _httpClient = new()
    {
        Timeout = TimeSpan.FromSeconds(6)
    };

    public static readonly string BaseUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    public async Task<BaiduTrans_TransResult?> GetTranslation(BaiduTransOptionModel config, BaiduTransModelVo data)
    {
        try
        {
            // 生成签名
            var salt = GenerateRandomSalt();
            var sign = GenerateSign(config.AppId, data.Value, salt, config.SecretKey);

            // 构建请求参数
            var queryParams = new Dictionary<string, string>
            {
                ["q"] = data.Value,
                ["from"] = data.From,
                ["to"] = data.To,
                ["appid"] = config.AppId,
                ["salt"] = salt,
                ["sign"] = sign
            };
            // 构建URL
            var url = QueryHelpers.AddQueryString(BaseUrl, queryParams);
            // 发送请求
            using var response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            // 读取响应
            var result = await response.Content.ReadAsStringAsync();
            var translationResult = JsonSerializer.Deserialize<BaiduTranslationResponse>(result);
            if (translationResult == null) throw new Exception("翻译结果为空!");
            if (translationResult.ErrorCode.IsNullOrWhiteSpace()) return translationResult?.TransResult.FirstOrDefault() ?? throw new Exception("翻译结果为空!");
            if (translationResult.ErrorCode == "54003") //访问频繁
                return null;
            throw new Exception($"翻译失败，错误码：{translationResult.ErrorCode}，错误信息：{translationResult.ErrorMsg}");
        }
        catch (Exception ex)
        {
            throw new Exception("翻译请求失败", ex);
        }
    }

    private static string GenerateRandomSalt()
    {
        return Random.Shared.Next(100000).ToString();
    }

    private static string GenerateSign(string appId, string text, string salt, string secretKey)
    {
        var signStr = appId + text + salt + secretKey;
        using var md5 = MD5.Create();
        var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(signStr));
        return BitConverter.ToString(hash).Replace("-", "").ToLower();
    }
}